package pdfsetter.ui;

import pdfsetter.core.XMLObjectSerializer;
import pdfsetter.core.schema.DocumentSchemaPattern;
import pdfsetter.core.schema.SimpleDocumentSchemaPattern;
import pdfsetter.core.schema.SinglePageSchema;
import pdfsetter.core.schema.advanced.FillingSchemaPattern;

import com.thoughtworks.xstream.XStreamException;

/**
 * This option is responsible for retrieving/preparing {@link DocumentSchemaPattern} according to which the files will be set. We can simply give xml file with
 * {@link DocumentSchemaPattern} or give {@link SinglePageSchema} and {@link FillingSchemaPattern} which will be joined to {@link SimpleDocumentSchemaPattern}.
 * 
 * @author Andrzej Dorobisz
 */
public class DocCommand implements PartCommand {
    private final XMLObjectSerializer serializer;
    private String[] args;
    private boolean initialized;

    public DocCommand(XMLObjectSerializer serializer) {
        this.serializer = serializer;
        this.initialized = false;
    }

    @Override
    public String getName() {
        return "-doc";
    }

    @Override
    public void printUsage(String indent) {
        System.out.println(indent + "-doc documentSchemaPattern.xml | singlePageSchema.xml fillingSchemaPattern.xml");
    }

    @Override
    public boolean setArgs(String[] args) {
        if ((args == null) || (args.length == 0) || (args.length > 2))
            return false;
        this.args = args;
        initialized = true;
        return true;
    }

    @Override
    public boolean isInitialized() {
        return initialized;
    }

    @Override
    public DocumentSchemaPattern process() throws ProcessCommandException {
        try {
            if (args.length == 1) {
                DocumentSchemaPattern docPattern = (DocumentSchemaPattern) serializer.readObject(args[0]);
                return docPattern;
            } else {
                SinglePageSchema pageSchema = (SinglePageSchema) serializer.readObject(args[0]);
                FillingSchemaPattern fillPattern = (FillingSchemaPattern) serializer.readObject(args[1]);
                return new SimpleDocumentSchemaPattern(pageSchema, fillPattern);
            }
        } catch (XStreamException xse) {
            throw new ProcessCommandException(xse);
        }
    }
}
